package com.ukao.cashregister.ui;

import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.hardware.display.DisplayManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.tencent.bugly.beta.Beta;
import com.ukao.cashregister.R;
import com.ukao.cashregister.base.BaseActivity;
import com.ukao.cashregister.bean.StringBean;
import com.ukao.cashregister.consts.Constant;
import com.ukao.cashregister.consts.SaveParamets;
import com.ukao.cashregister.dialog.PrintHideDialogFragment;
import com.ukao.cashregister.dialog.QuitLoginDialogFragment;
import com.ukao.cashregister.eventbus.MembershipCardEvent;
import com.ukao.cashregister.retrofit.ApiCallback;
import com.ukao.cashregister.ui.login.LoginActivity;
import com.ukao.cashregister.usbrfidreader.UsbrfidreaderHelper;
import com.ukao.cashregister.utils.CheckUtils;
import com.ukao.cashregister.utils.ImageUtils;
import com.ukao.cashregister.utils.T;
import com.ukao.cashregister.widget.ShapedImageView;

import org.greenrobot.eventbus.Subscribe;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import woyou.aidlservice.jiuiv5.ICallback;
import woyou.aidlservice.jiuiv5.IWoyouService;

import static com.ukao.cashregister.R.id.left_control_menu_netstat;

public class MainActivity extends BaseActivity {


    @BindView(left_control_menu_netstat)
    ImageView netstat;
    @BindView(R.id.left_control_menu_shopname)
    TextView shopname;
    @BindView(R.id.left_control_menu_icon)
    ShapedImageView menuIcon;
    @BindView(R.id.left_control_menu_username)
    TextView username;
    @BindView(R.id.left_control_menu_play_money)
    Button playMoney;
    @BindView(R.id.left_control_menu_remind)
    Button menuRemind;
    @BindView(R.id.left_control_menu_remind_count)
    TextView remindCount;
    @BindView(R.id.left_control_menu_exit)
    Button menuExit;
    @BindView(R.id.contentFrame)
    FrameLayout contentFrame;

    private static IWoyouService woyouService;
    private HomeFragment mHomeFragment;
    private WifiReceiver mReceiver;
    private WifiManager mWifiManager;
    private PrintHideDialogFragment mPrintHideDialog;

    private DisplayManager mDisplayManager;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);//false,false
        if (!CheckUtils.isMIUIDevices()) {
            Beta.checkUpgrade(false, false);/*不提示正在检查更新，2不弹提示*/
        }
        initView();
        startMiuiServiceIntent();
    }


    /**
     * 开启小米打印服务
     */
    private void startMiuiServiceIntent() {
        if (CheckUtils.isMIUIDevices()) {
            Intent intent = new Intent();
            intent.setPackage("woyou.aidlservice.jiuiv5");
            intent.setAction("woyou.aidlservice.jiuiv5.IWoyouService");
            startService(intent);//启动打印服务
            bindService(intent, connService, Context.BIND_AUTO_CREATE);
        }

    }

    private ServiceConnection connService = new ServiceConnection() {

        @Override
        public void onServiceDisconnected(ComponentName name) {
            woyouService = null;
        }

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            woyouService = IWoyouService.Stub.asInterface(service);
        }
    };


    public static IWoyouService getPrintService() {
        return woyouService;
    }


    @Override
    protected void initView() {

        mWifiManager = (WifiManager) this.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        mHomeFragment = new HomeFragment();
        loadRootFragment(R.id.contentFrame, mHomeFragment);
        username.setText(SaveParamets.getSaveUseName(this));
        ImageUtils.loadImage(this, SaveParamets.getHeadimgPath(this), menuIcon, R.drawable.left_control_menu_icon);
        shopname.setText(SaveParamets.getStoreName());
        if (CheckUtils.isMIUIDevices()) {
            playMoney.setVisibility(View.VISIBLE);
        } else {
            playMoney.setVisibility(View.INVISIBLE);
        }

    }


    @Override
    protected void onResume() {
        super.onResume();
        netstat.setImageResource(mWifiManager.isWifiEnabled() ? R.drawable.left_control_menu_wifi : R.drawable.left_control_menu_no_wifi);
        registerReceiver();


    }

    @Override
    protected void onPause() {
        super.onPause();
        unregisterReceiver(mReceiver);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (UsbrfidreaderHelper.mRfidHelper != null) {
            UsbrfidreaderHelper.getInstance().onDestroy();
        }

        if (CheckUtils.isMIUIDevices() && woyouService != null) {
            try {
                unbindService(connService);
            } catch (Exception e) {

            }

        }

    }

    @OnClick({R.id.left_control_menu_play_money, R.id.left_control_menu_remind, R.id.left_control_menu_remind_count,
            R.id.left_control_menu_exit, R.id.left_control_menu_icon, R.id.left_control_menu_netstat})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.left_control_menu_icon:
                QuitLoginDialogFragment quitLoginDialog = new QuitLoginDialogFragment();
                quitLoginDialog.show(getSupportFragmentManager(), QuitLoginDialogFragment.class.getName());
                break;
            case R.id.left_control_menu_play_money:/*钱箱*/
                if (CheckUtils.isMIUIDevices() && null != woyouService) {
                    byte[] aa = new byte[5];
                    aa[0] = 0x10;
                    aa[1] = 0x14;
                    aa[2] = 0x00;
                    aa[3] = 0x00;
                    aa[4] = 0x00;
                    try {
                        woyouService.sendRAWData(aa, new ICallback() {
                            @Override
                            public void onRunResult(boolean isSuccess) throws RemoteException {

                            }

                            @Override
                            public void onReturnString(String result) throws RemoteException {

                            }

                            @Override
                            public void onRaiseException(int code, String msg) throws RemoteException {

                            }

                            @Override
                            public IBinder asBinder() {
                                return null;
                            }
                        });
                    } catch (RemoteException e1) {
                        e1.printStackTrace();
                    }
                }
                break;
            case R.id.left_control_menu_remind:
                break;
            case R.id.left_control_menu_remind_count:
                break;
            case R.id.left_control_menu_exit:
                int count = getSupportFragmentManager().getBackStackEntryCount();
                if (count > 1)
                    popTo(HomeFragment.class, false);

                break;
            case left_control_menu_netstat:/*无线网*/
                HomeFragment mHomeFragment = findFragment(HomeFragment.class);
                if (mHomeFragment != null) {
                    mHomeFragment.startWifiFrament();
                }
                break;
        }
    }


    @Override
    public void onBackPressedSupport() {

        if (getSupportFragmentManager().getBackStackEntryCount() > 1) {
            pop();
        }
    }


    @Override
    protected boolean useEventBus() {
        return true;
    }

    @Subscribe
    public void onEvent(MembershipCardEvent event) {
        switch (event.getMessage()) {
            case login:
                SaveParamets.setIslogin(false);
                startloginActivity();

                break;
            case quit:

                quitout();

                break;
            case print:
                Map mMap = (Map) event.getData();
                String deviceName = (String) mMap.get(ARG_PARAM1);
                String printMachine = (String) mMap.get(ARG_PARAM2);
                showPrinterDialog(deviceName, printMachine);
                break;
            case back_home:
                popTo(HomeFragment.class, false);
                break;


        }

    }

    public void showPrinterDialog(String deviceName, String printMachine) {
        if (mPrintHideDialog == null) {
            mPrintHideDialog = new PrintHideDialogFragment();
        }
        Bundle mBundle = new Bundle();
        mBundle.putString(ARG_PARAM1, deviceName);
        mBundle.putString(ARG_PARAM2, printMachine);
        mPrintHideDialog.setArguments(mBundle);
        mPrintHideDialog.show(getSupportFragmentManager(), PrintHideDialogFragment.class.getName());
    }


    public void startloginActivity() {
        Intent intent = new Intent(this, LoginActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
        this.startActivity(intent);
    }

    /**
     * 退出
     */
    public void quitout() {

        showProgressDialog();
        HashMap mHashMap = new HashMap<String, String>();
        mHashMap.put("accessToken", SaveParamets.getToken(this));
        addSubscription(apiStores().logout(Constant.createParameter(mHashMap)),
                new ApiCallback<StringBean>() {
                    @Override
                    public void onSuccess(StringBean model) {

                        if (model.getHttpCode() == 200) {

                        }
                    }


                    @Override
                    public void onFinish() {
                        dismissProgressDialog();
                        SaveParamets.setIslogin(false);
                        startloginActivity();
                    }
                });
    }

    /**
     * 注册wifi 广播
     */
    private void registerReceiver() {
        mReceiver = new WifiReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
        filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
        filter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
        filter.addAction(WifiManager.SUPPLICANT_STATE_CHANGED_ACTION);
        filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        registerReceiver(mReceiver, filter);
    }

    private class WifiReceiver extends BroadcastReceiver {
        protected static final String TAG = "ukao";


        @Override
        public void onReceive(Context context, Intent intent) {

            if (intent.getAction().equals(WifiManager.NETWORK_STATE_CHANGED_ACTION)) {// wifi连接上与否
                Log.d(TAG, "网络已经改变");

                NetworkInfo info = intent
                        .getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
                if (info.getState().equals(NetworkInfo.State.DISCONNECTED)) {
                    Log.d(TAG, "wifi已经断开");
                    netstat.setImageResource(R.drawable.left_control_menu_no_wifi);

                } else if (info.getState().equals(NetworkInfo.State.CONNECTING)) {
                    Log.d(TAG, "正在连接...");
                    netstat.setImageResource(R.drawable.left_control_menu_no_wifi);

                } else if (info.getState().equals(NetworkInfo.State.CONNECTED)) {
                    WifiManager wifiManager = (WifiManager) context
                            .getSystemService(Context.WIFI_SERVICE);
                    WifiInfo wifiInfo = wifiManager.getConnectionInfo();
                    Log.d(TAG, "连接到网络：" + wifiInfo.getBSSID());
                    netstat.setImageResource(R.drawable.left_control_menu_wifi);
                }

            } else if (intent.getAction().equals(WifiManager.SUPPLICANT_STATE_CHANGED_ACTION)) {
                int error = intent.getIntExtra(WifiManager.EXTRA_SUPPLICANT_ERROR,
                        0);

                switch (error) {

                    case WifiManager.ERROR_AUTHENTICATING:
                        Log.d(TAG, "密码认证错误Code为：" + error);
                        T.show("密码认证错误");
                        break;
                    default:
                        break;
                }

            }
        }

    }


}
